# -*- coding: utf-8 -*-
"""
推箱子关卡预览图片生成器
根据关卡数据生成可视化的预览图片
"""

import pygame
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# 引入自定义关卡资源
from 关卡.tuixiangzi01 import levels_all

# 初始化Pygame
pygame.init()

# 增加窗口和右侧栏宽度
TILE_SIZE = 24  # 缩小格子大小以适应更大地图
LEVEL_WIDTH = 16 * TILE_SIZE
LEVEL_HEIGHT = 16 * TILE_SIZE
# 缩小地图之间的间距
GAP = 2
# 增加右侧地图右边的白色空隙
RIGHT_GAP = 32
# 增加窗口高度和底部空隙
BOTTOM_GAP = 32
INFO_PANEL_WIDTH = 280  # 右侧说明栏宽度加大
WIDTH = LEVEL_WIDTH * 2 + GAP + INFO_PANEL_WIDTH + RIGHT_GAP  # 增加右侧说明栏宽度和关卡间隙
# 增加窗口高度和底部空隙
HEIGHT = LEVEL_HEIGHT * 2 + GAP + BOTTOM_GAP
FPS = 60

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (128, 128, 128)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
BROWN = (165, 42, 42)
PURPLE = (128, 0, 128)
LIGHT_GREY = (200, 200, 200)  # 用于层次显示效果

# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("推箱子关卡预览")

# 设置字体 - 使用系统中文字体确保中文正常显示
try:
    font = pygame.font.SysFont('SimHei', 20)
    font_big = pygame.font.SysFont('SimHei', 24)
except:
    font = pygame.font.Font(None, 20)
    font_big = pygame.font.Font(None, 24)


def draw_cell(surface, cell_value, x, y):
    rect = pygame.Rect(x, y, TILE_SIZE, TILE_SIZE)
    pygame.draw.rect(surface, GREY, rect, 1)
    if cell_value == 5:  # 箱子在目标点
        pygame.draw.circle(surface, GREEN, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 3)
        pygame.draw.circle(surface, BLACK, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 3, 2)
        box_rect = pygame.Rect(x + 4, y + 4, TILE_SIZE - 8, TILE_SIZE - 8)
        pygame.draw.rect(surface, BLUE, box_rect)
        pygame.draw.rect(surface, BLACK, box_rect, 2)
        pygame.draw.line(surface, BLACK, (x + 8, y + 8), (x + TILE_SIZE - 8, y + TILE_SIZE - 8), 2)
        pygame.draw.line(surface, BLACK, (x + TILE_SIZE - 8, y + 8), (x + 8, y + TILE_SIZE - 8), 2)
        pygame.draw.circle(surface, YELLOW, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 6)
    elif cell_value == 6:  # 玩家在目标点
        pygame.draw.circle(surface, GREEN, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 3)
        pygame.draw.circle(surface, BLACK, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 3, 2)
        pygame.draw.circle(surface, RED, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 4)
        pygame.draw.circle(surface, BLACK, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 4, 2)
    elif cell_value == 4:  # 玩家
        pygame.draw.circle(surface, RED, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 3)
        pygame.draw.circle(surface, BLACK, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 3, 2)
    elif cell_value == 2:  # 箱子
        box_rect = pygame.Rect(x + 4, y + 4, TILE_SIZE - 8, TILE_SIZE - 8)
        pygame.draw.rect(surface, BLUE, box_rect)
        pygame.draw.rect(surface, BLACK, box_rect, 2)
        pygame.draw.line(surface, BLACK, (x + 8, y + 8), (x + TILE_SIZE - 8, y + TILE_SIZE - 8), 2)
        pygame.draw.line(surface, BLACK, (x + TILE_SIZE - 8, y + 8), (x + 8, y + TILE_SIZE - 8), 2)
    elif cell_value == 3:  # 目标点
        pygame.draw.circle(surface, GREEN, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 3)
        pygame.draw.circle(surface, BLACK, (x + TILE_SIZE // 2, y + TILE_SIZE // 2), TILE_SIZE // 3, 2)
    elif cell_value == 1:  # 墙
        pygame.draw.rect(surface, BROWN, rect)
        pygame.draw.rect(surface, BLACK, rect, 1)


def draw_empty_level(surface, offset_x, offset_y):
    bg_rect = pygame.Rect(offset_x, offset_y, LEVEL_WIDTH, LEVEL_HEIGHT)
    pygame.draw.rect(surface, LIGHT_GREY, bg_rect)
    pygame.draw.rect(surface, GREY, bg_rect, 2)
    border_color = (255, 255, 255)
    border_width = 6
    pygame.draw.line(surface, border_color, (offset_x, offset_y), (offset_x + LEVEL_WIDTH, offset_y), border_width)
    pygame.draw.line(surface, border_color, (offset_x, offset_y), (offset_x, offset_y + LEVEL_HEIGHT), border_width)
    pygame.draw.line(surface, border_color, (offset_x + LEVEL_WIDTH, offset_y), (offset_x + LEVEL_WIDTH, offset_y + LEVEL_HEIGHT), border_width)
    pygame.draw.line(surface, border_color, (offset_x, offset_y + LEVEL_HEIGHT), (offset_x + LEVEL_WIDTH, offset_y + LEVEL_HEIGHT), border_width)


def draw_single_level(surface, level, level_num, offset_x, offset_y):
    gap = 16
    offset_x += gap // 2
    offset_y += gap // 2
    border_rect = pygame.Rect(offset_x - 2, offset_y - 2, LEVEL_WIDTH + 4, LEVEL_HEIGHT + 4)
    pygame.draw.rect(surface, LIGHT_GREY, border_rect)
    pygame.draw.rect(surface, (255, 255, 255), border_rect, 6)
    for row in range(16):
        for col in range(16):
            x = offset_x + col * TILE_SIZE
            y = offset_y + row * TILE_SIZE
            draw_cell(surface, level[row][col], x, y)
    cn_levels = ["第一关", "第二关", "第三关", "第四关", "第五关", "第六关", "第七关", "第八关", "第九关", "第十关", "第十一关", "第十二关", "第十三关", "第十四关", "第十五关", "第十六关", "第十七关", "第十八关", "第十九关", "第二十关"]
    level_name = cn_levels[level_num-1] if level_num <= len(cn_levels) else f"第{level_num}关"
    level_text = font.render(level_name, True, (255, 255, 255))
    text_x = offset_x + (LEVEL_WIDTH - level_text.get_width()) // 2
    text_y = offset_y + (TILE_SIZE - level_text.get_height()) // 2
    surface.blit(level_text, (text_x, text_y))


def draw_levels(levels_start_index):
    main_area = pygame.Rect(0, 0, LEVEL_WIDTH * 2 + GAP + RIGHT_GAP, HEIGHT)
    pygame.draw.rect(screen, WHITE, main_area)
    levels_to_show = min(4, len(levels_all) - levels_start_index)
    for i in range(4):
        row = i // 2
        col = i % 2
        gap = 16
        offset_x = col * (LEVEL_WIDTH + gap)
        offset_y = row * (LEVEL_HEIGHT + gap)
        if i < levels_to_show and (levels_start_index + i) < len(levels_all):
            draw_single_level(screen, levels_all[levels_start_index + i], levels_start_index + i + 1, offset_x, offset_y)
        else:
            draw_empty_level(screen, offset_x, offset_y)
    # 显示页面信息和操作说明到右侧栏
    info_area = pygame.Rect(LEVEL_WIDTH * 2 + GAP + RIGHT_GAP, 0, INFO_PANEL_WIDTH, HEIGHT)
    pygame.draw.rect(screen, LIGHT_GREY, info_area)
    pygame.draw.line(screen, BLACK, (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP, 0), (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP, HEIGHT), 2)

    # 添加说明文字
    info_title = font_big.render("预览说明", True, (0, 0, 0))
    screen.blit(info_title, (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP + INFO_PANEL_WIDTH // 2 - info_title.get_width() // 2, 20))

    info_lines = [
        "元素说明:",
        "■ 墙壁（红色）",
        "● 玩家（红色）",
        "◎ 目标点（绿色）",
        "◆ 箱子（蓝色）",
        "◆◎ 箱子在目标点（黄蓝色）",
        "●◎ 玩家在目标点（红绿色）",
        "",
        "操作说明:",
        "↑↓←→ 切换页面",
        "ESC 退出程序"
    ]
    for i, line in enumerate(info_lines):
        info_text = font.render(line, True, (0, 0, 0))
        screen.blit(info_text, (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP + 10, 60 + i * 25))

    # 显示页面信息
    page_num = levels_start_index // 4 + 1
    total_pages = (len(levels_all) + 3) // 4  # 向上取整
    page_text = font.render(f"页面 {page_num}/{total_pages}", True, (0, 0, 0))
    screen.blit(page_text, (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP + INFO_PANEL_WIDTH // 2 - page_text.get_width() // 2, HEIGHT - 40))

    pygame.display.flip()


def main():
    """
    主函数 - 显示关卡预览或保存所有关卡图片
    """
    clock = pygame.time.Clock()

    # 直接进入实时预览模式，避免input导致的无响应
    current_page = 0
    running = True

    # 显示初始提示信息
    screen.fill(WHITE)
    hint1 = font_big.render("推箱子关卡预览工具", True, BLACK)
    hint2 = font.render("方向键切换页面, ESC退出", True, BLACK)
    hint3 = font.render("正在加载关卡...", True, BLACK)
    screen.blit(hint1, (LEVEL_WIDTH - hint1.get_width() // 2, HEIGHT // 2 - 30))
    screen.blit(hint2, (LEVEL_WIDTH - hint2.get_width() // 2, HEIGHT // 2))
    screen.blit(hint3, (LEVEL_WIDTH - hint3.get_width() // 2, HEIGHT // 2 + 30))

    # 绘制右侧说明栏
    info_area = pygame.Rect(LEVEL_WIDTH * 2 + GAP + RIGHT_GAP, 0, INFO_PANEL_WIDTH, HEIGHT)
    pygame.draw.rect(screen, LIGHT_GREY, info_area)
    pygame.draw.line(screen, BLACK, (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP, 0), (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP, HEIGHT), 2)

    # 添加说明文字
    info_title = font_big.render("预览说明", True, BLACK)
    screen.blit(info_title, (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP + INFO_PANEL_WIDTH // 2 - info_title.get_width() // 2, 20))

    info_lines = [
        "元素说明:",
        "■ 墙壁（红色）",
        "● 玩家（红色）",
        "◎ 目标点（绿色）",
        "◆ 箱子（蓝色）",
        "◆◎ 箱子在目标点（黄色）",
        "●◎ 玩家在目标点（红绿色）",
        "",
        "操作说明:",
        "↑↓←→ 切换页面",
        "ESC 退出程序"
    ]

    for i, line in enumerate(info_lines):
        info_text = font.render(line, True, BLACK)
        screen.blit(info_text, (LEVEL_WIDTH * 2 + GAP + RIGHT_GAP + 10, 60 + i * 25))

    pygame.display.flip()

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_RIGHT or event.key == pygame.K_DOWN:
                    current_page = (current_page + 1) % ((len(levels_all) + 3) // 4)
                elif event.key == pygame.K_LEFT or event.key == pygame.K_UP:
                    current_page = (current_page - 1) % ((len(levels_all) + 3) // 4)

        # 绘制当前页面的关卡（最多4个）
        draw_levels(current_page * 4)
        clock.tick(FPS)

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()